<!--  TODO 单选应用场景较少，后续继续封装 -->
<script setup lang="ts">
import { Field, Checkbox, CheckboxGroup } from "vant";
import { watch, computed } from "vue";
import checkall from "./images/allChecked.png";
import checkhalf from "./images/halfChecked.png";
import checkno from "./images/noCheck.png";

// 复选数据格式
type dataInfo = {
  key: string | number;
  name: string;
};

interface PropsData {
  modelValue: any[]; // 选中值
  checkedDatas: dataInfo[]; // 多选时的选项
  label?: string | number; //全选半选文字
}

// 父组件传参
const propsData = defineProps<PropsData>();

const emits = defineEmits<{
  (e: "update:modelValue", val: any[]): void;
}>();

// 已勾选的值
const groupChecked = computed({
  get: () => propsData.modelValue,
  set: (val) => {
    emits("update:modelValue", val);
  },
});

// 组内单选
const checkboxChange = function (names: any[]) {
  console.log(names);
};

// 全选半选
const groupCheckChange = function () {
  if (groupChecked.value.length < propsData.checkedDatas.length) {
    propsData.checkedDatas.forEach((x: dataInfo) => {
      if (groupChecked.value.indexOf(x.key) === -1) {
        groupChecked.value.push(x.key);
      }
    });
  } else {
    groupChecked.value.length = 0;
  }
};

// 全选半选样式值
const getCheckImg = computed(() => {
  if (groupChecked.value.length === propsData.checkedDatas.length) {
    return checkall;
  } else if (
    groupChecked.value.length > 0 &&
    groupChecked.value.length < propsData.checkedDatas.length
  ) {
    return checkhalf;
  } else {
    return checkno;
  }
});
const getChecks = computed(() => {
  return propsData.modelValue.toString();
});
</script>
<template>
  <field name="txt" v-model="getChecks">
    <template #input>
      <checkbox @click="groupCheckChange" v-if="propsData.label">
        {{ propsData.label }}
        <template #icon>
          <img class="img-icon" :src="getCheckImg" />
        </template>
      </checkbox>
      <checkbox-group
        v-model="groupChecked"
        ref="checkboxGroup"
        @change="checkboxChange"
      >
        <checkbox
          v-for="item in propsData.checkedDatas"
          :key="item.key"
          :name="item.key"
        >
          {{ item.name }}
        </checkbox>
      </checkbox-group>
    </template>
  </field>
</template>

<style lang="scss" scoped>
.img-icon {
  width: 21px;
  height: 21px;
}

.van-checkbox {
  height: 48px;
  line-height: 48px;
  border-bottom: 1px solid #eeeeee;
}
</style>
